'use strict';

var successCallback = function() {

};
var errorCallback = function(param) {
    $("div#alert").html(
            '<div class="alert">' +
                '<button type="button" class="close" data-dismiss="alert">&times;</button>' +
                '<strong>Warning! </strong>' + param.data +
            '</div>'
        );
};
var fill = function($scope, name, Entity) {
    $scope.entityName = name
    $scope.meta =  Entity.getMeta({entity: $scope.entityName},
        successCallback,
        errorCallback);    
}

function EntityTableCtrl($scope, $routeParams, Entity) {
    fill($scope, $routeParams.entity, Entity);
    $scope.entity = Entity.getAll({entity: $scope.entityName},
        successCallback,
        errorCallback);
    $scope.orderProp = "id";
}
function EntityAddCtrl($scope, $location, $routeParams, Entity) {
    fill($scope, $routeParams.entity, Entity);
    $scope.entity = { entityName: $scope.entityName };
    
    $scope.save = function() {
        Entity.create($scope.entity,
            successCallback,
            errorCallback);
        $location.path($scope.entityName + "/table");
    }
}
function EntityEditCtrl($scope, $routeParams, $location, Entity) {
    fill($scope, $routeParams.entity, Entity);    
    $scope.id = $routeParams.id
    $scope.entity = Entity.get({entity: $scope.entityName, id: $scope.id},
        successCallback,
        errorCallback);

    $scope.save = function() {
        // adding entity name because the save method needs this param to construct the URL;
        $scope.entity.entityName = $scope.entityName;
        Entity.save($scope.entity,
            function () { // success
                console.log($scope.entityName + " updated!")
            },
            errorCallback);
        $location.path($scope.entityName + "/table");
    }
    $scope.delete = function() {
        var answer = confirm("Are you sure you want to delete \"" + $scope.entity.id + "\"?"); //TODO add something more relevant!
        if (answer) {
            Entity.delete({entity: $scope.entityName, id: $scope.id},
                function () { // success
                    console.log($scope.entityName + " deleted!");
                },
                errorCallback);
            $location.path($scope.entityName + "/table");
        }
    }
}